<!--
 * @Author: dumin 173672326@qq.com
 * @Date: 2025-03-13 15:28:58
 * @LastEditors: dumin 173672326@qq.com
 * @LastEditTime: 2025-03-21 12:09:15
 * @Description: 带有搜索功能导入导出参会人员（会议投票/参会人员）
-->
<template>
  <div class="search-export-import-users">
    <div class="view-scope">
      <div class="app-flex-mid app-flex-space-between view-scope__header">
        <div class="app-flex-mid view-scope__header--import">
          <el-input v-model="userName" placeholder="请输入参会人员姓名" />
          <el-button type="primary" @click="handleSearch()">搜索</el-button>
          <div class="search-wrapper">
            <el-button type="primary" @click="handleSearch('reset')">重置</el-button>
          </div>
        </div>

        <div class="app-flex-mid">
          <DownloadTemplate file-name="参会人员.xlsx" />
          <ImportUpload :attr="{ type: 'success', icon: '', plain: true }" @change="onChange" />
          <el-button :loading="exportLoading" type="warning" plain @click="handleExport">导出</el-button>
          <slot name="action-right"></slot>
          <div class="total-wrapper">共计：{{ list.length }}人</div>
        </div>
      </div>
      <div class="view-scope__table">
        <el-table :data="list">
          <el-table-column prop="mobile" label="手机号" />
          <el-table-column prop="name" label="人员姓名" />
          <template v-if="showJobSwitch">
            <el-table-column prop="jobTitle">
              <template #header>
                <div class="app-flex-mid job-switch">
                  <span>职务</span>
                  <el-switch
                    class="job-switch__btn"
                    style="--el-switch-off-color: #ccc"
                    v-model="showJobTitle"
                  />
                </div>
              </template>
            </el-table-column>
          </template>
          <template v-else>
            <el-table-column prop="jobTitle" label="职务" />
          </template>
          <el-table-column prop="company" label="所属单位" />
          <el-table-column prop="role" label="参会角色" />
          <el-table-column label="操作">
            <template #default="scope">
              <el-button type="primary" link @click="handleDelete(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <div style="display: none">用于数据更新{{ originList }}</div>
  </div>
</template>

<script setup>
import { dayjs } from 'element-plus'
import ImportUpload from '@/components/form/ImportUpload.vue'
import DownloadTemplate from '@/components/form/DownloadTemplate.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { http } from 'jax-node'

defineProps({
  showJobSwitch: { type: Boolean, default: false },
})

const model = defineModel({ type: Array, default: [] })
const showJobTitle = defineModel('showJobTitle', { type: Boolean, default: false })

const fields = ['mobile', 'name', 'jobTitle', 'company', 'role']
const fieldsEnum = {
  mobile: '手机号',
  name: '人员姓名',
  jobTitle: '职务',
  company: '所属单位',
  role: '参会角色',
}

const list = ref([])
const originList = computed({
  get() {
    list.value = model.value
    return model.value
  },
  set(val) {
    model.value = val
  },
})

const onChange = reslut => {
  if (reslut.length > 1) {
    list.value = originList.value = reslut.slice(1).map(row => {
      const obj = {}
      fields.forEach((field, index) => {
        obj[field] = row[index]
      })
      return obj
    })
  } else {
    ElMessage.error('请上传正确的格式的文件')
  }
}

const handleDelete = index => {
  ElMessageBox.confirm('是否确定删除该成员?', '温馨提示', {
    type: 'warning',
  }).then(() => {
    list.value.splice(index, 1)
    originList.value = [...list.value]
  })
}

// 导出
const exportLoading = ref(false)
const handleExport = () => {
  // 生成表头
  const header = fields.map(field => fieldsEnum[field])
  // 生成每一行的数据
  const rows = list.value.map(item => fields.map(field => item[field] ?? ''))
  // 合并
  const result = [header, ...rows]
  exportLoading.value = true
  http({
    url: '/system/file/export-xlsx',
    method: 'POST',
    data: {
      data: result,
    },
  })
    .then(res => {
      const importFileUrl = res.url.slice(res.url.indexOf('/temp/'))
      fetch(importFileUrl, { method: 'GET' })
        .then(response => response.blob())
        .then(blob => {
          const url = window.URL.createObjectURL(blob)
          const a = document.createElement('a')
          a.href = url
          a.download = `${dayjs().format('YYYY-MM-DD_HH_mm_ss')}-人员列表.xlsx`
          document.body.appendChild(a)
          a.click()
          document.body.removeChild(a)
          ElMessage.success('操作成功')
        })
    })
    .finally(() => {
      exportLoading.value = false
    })
}

// 搜索条件
const userName = ref('')
const handleSearch = type => {
  const lists = originList.value
  if (type === 'reset') {
    userName.value = ''
    list.value = lists
    return
  }
  list.value = lists.filter(item => item.name.includes(userName.value))
}
</script>

<style lang="scss" scoped>
.search-export-import-users {
  .view-scope {
    &__header {
      margin-bottom: 15px;
      &--import {
        gap: 15px;
      }
    }
  }
  .total-wrapper {
    margin-left: 10px;
  }
}
</style>
